package grupobbva.pe.operhc.service;

import static grupobbva.pe.operhc.util.Constant.TIPO_ARCHIVO_DISCLAMER;

import java.util.Map;


import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;

public class ActualizarQuartzServiceImpl implements ActualizarQuartzService {
	private static Logger logger = Logger.getLogger(CuadroMandoServiceImpl.class);
		
	private ParametroService parametrosService = null;
	

	public ActualizarQuartzServiceImpl() {
		parametrosService = new ParametroServiceImpl();
	}
	public void actualizarConfiguracionQuartz(){
		String nombreServicio="";
		try {
			
			
			SchedulerFactory schFactory = new StdSchedulerFactory();
	        Scheduler schedulerFactoyBean = schFactory.getScheduler();
	
			nombreServicio="ServicioCargaDisclamer";
			
			logger.info("Inicio Actualizacion de Cron****** " + nombreServicio);
			
			try {
				logger.info("******Obteniendo Informacion del Monitor");
				if(schedulerFactoyBean.isInStandbyMode()){
					logger.info("*********Monitor is In Stand By Mode");
				}
				if(schedulerFactoyBean.isShutdown()){
					logger.info("*********Monitor is Shutdown");
				}
				
			} catch (Exception e) {
				logger.error("********Ocurrio un error obteniendo informacion del cron monitor");
				
			}
					 
			Map<String, String> parametroBroker = parametrosService.getMapParametersByParameterType(TIPO_ARCHIVO_DISCLAMER);
			String strCron = parametroBroker.get("CRON_TRIGGER");
			if (strCron==null ||(strCron!=null && strCron.equals(""))){
				strCron="0 0 04 * * ?";
			}
						
			logger.info("**********************CRON:"+strCron+"*******************");
			
			String strNombreTrigger = "CronTriggerDisclamer";			
			
			// retrieve the trigger
			TriggerKey triggerKey=new TriggerKey(strNombreTrigger,schedulerFactoyBean.DEFAULT_GROUP);
			Trigger oldTrigger = schedulerFactoyBean.getTrigger(triggerKey);
			
			// obtain a builder that would produce the trigger
			TriggerBuilder tb = oldTrigger.getTriggerBuilder();
			Trigger newTrigger = tb.withSchedule(CronScheduleBuilder.cronSchedule(strCron)).build();

			
			if(oldTrigger!=null){
				schedulerFactoyBean.rescheduleJob(oldTrigger.getKey(), newTrigger);			
			}else{
				logger.info("**********Ocurrio un Problema al cambiar Cron");
			}
			 			
		} catch (Exception e) {
			
			logger.error("Exception actua cron:"+e.getMessage());
		}
		logger.info("Fin Actualizacion de Cron****** " + nombreServicio);
		
		
	}
	
	

}
